package com.ruoyi.miaomiao.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.WxLoginService;
import com.ruoyi.framework.web.service.WxUser;
import com.ruoyi.miaomiao.domain.CommonUser;
import com.ruoyi.miaomiao.service.ICommonUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController {
    private final WxMaService wxMaService;

    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private ICommonUserService iUserService;


    /**
     * 微信授权，授权成功的标志是用户表中拥有用户昵称，如果未授权，用户昵称为空
     * @param user   前端返回的有关微信用户数据
     * @param request  提供token,获取redis存储的用户信息
     * @return
     */
    @PostMapping("/postAuth")
    public R postAuth(@RequestBody CommonUser user, HttpServletRequest request){
        String token = wxLoginService.getToken(request);
        WxUser wxUser = wxLoginService.getWxUser(token);
        wxUser.setUserName(user.getUserName());
        wxLoginService.setWxUser(wxUser);

        //查询出数据库中用户信息，并进行修改
        CommonUser dbUser = iUserService.selectCommonUserByOpenId(wxUser.getOpenId());
        dbUser.setUserName(user.getUserName());
        //前端传的数据为“false"---女
        dbUser.setUserSex(user.getUserSex().equals("false")== true ? "0" :"1");

        iUserService.updateCommonUser(dbUser);


        return R.ok("授权成功！");
    }

    /**
     * 用户登陆
     * @param appid   小程序appid
     * @param code    小程序code
     * @param token   微信用户令牌token
     * @return
     */
    @GetMapping("/login")
    public R login(@PathVariable String appid, String code, String token) {
        //System.out.println("token:" + token);
        WxUser wxUser = null;
        if(StringUtils.isNotEmpty(token)){
            wxUser = wxLoginService.getWxUser(token);
        }

        if (StringUtils.isNull(wxUser)){
            //不存在该用户
            if (StringUtils.isBlank(code)) {
                return R.fail("empty jscode");
            }
            if (!wxMaService.switchover(appid)) {
                throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
            }
            try {
                WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
                log.info(session.getSessionKey());
                log.info(session.getOpenid());
                //
                wxUser = new WxUser();
                wxUser.setOpenId(session.getOpenid());
                String openId = wxUser.getOpenId();
                // 通过openId查询后端用户表中的数据
                CommonUser user = iUserService.selectCommonUserByOpenId(openId);
                if (StringUtils.isNotNull(user)){
                    if(!"未知".equals(user.getUserName())){
                        //已经登录过，用户不为“未知”，直接登录
                        wxUser.setUserName(user.getUserName());

                        String newToken = wxLoginService.createToken(wxUser);
                        wxLoginService.setWxUser(wxUser);
                        HashMap<String, Object> map = setData(newToken, user);
                        return R.ok(map, "登录成功");
                    }else {
                        //非首次，尝试登陆过，但未授权。
                        String newToken = wxLoginService.createToken(wxUser);
                        HashMap<String, Object> map = setData(newToken, null);
                        return R.fail(map, "微信请授权");
                    }
                }else {
                    //首次登录
                    String newToken = wxLoginService.createToken(wxUser);
                    CommonUser newUser = new CommonUser();
                    newUser.setUserOpenid(openId);
                    iUserService.insertCommonUser(newUser);
                    HashMap<String, Object> map = setData(newToken, null);
                    return R.fail(map, "未登录过，请授权");
                }

            } catch (WxErrorException e) {
                log.error(e.getMessage(), e);
                return R.fail(e.toString());
            } finally {
                WxMaConfigHolder.remove();//清理ThreadLocal
            }
        }else{
            //token, wxUser都不为空
            String nickName = wxUser.getUserName();//昵称为“未知”，未授权
            if(!"未知".equals(nickName)){
                CommonUser user = iUserService.selectCommonUserByOpenId(wxUser.getOpenId());
                //更新缓存
                wxLoginService.setWxUser(wxUser);
                HashMap<String, Object> map = setData(token, user);
                return R.ok(map, "登录成功");
            }else {
                //昵称为未知，即需要授权
                wxLoginService.setWxUser(wxUser);
                HashMap<String, Object> map = setData(token, null);
                return R.fail(map, "未完成登录过，请授权");
            }
        }
    }


    private HashMap<String, Object> setData(String token, CommonUser user){
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        return map;
    }

//    /**
//     * <pre>
//     * 获取用户信息接口
//     * </pre>
//     */
//    @GetMapping("/info")
//    public String info(@PathVariable String appid, String sessionKey,
//                       String signature, String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密用户信息
//        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(userInfo);
//    }
//
//    /**
//     * <pre>
//     * 获取用户绑定手机号信息
//     * </pre>
//     */
//    @GetMapping("/phone")
//    public String phone(@PathVariable String appid, String sessionKey, String signature,
//                        String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密
//        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(phoneNoInfo);
//    }

}
